package com.hm.PushCaseService.control;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.hm.PushCaseService.framework.service.base.IBaseService;
import com.hm.PushCaseService.framework.service.token.ITokenService;
import com.hm.PushCaseService.pojo.response.UserBean;
import com.hm.PushCaseService.service.user.IUserService;
import com.hm.PushCaseService.service.valve.IValveService;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;


@RestController
@RequestMapping(value = "/main", produces = {"application/json;charset=UTF-8"})
public class PCS_000_000_010<T> {

    private static final Logger logger = LoggerFactory.getLogger(PCS_000_000_010.class);

    private final IBaseService<String> iBaseService;

    private final ITokenService iTokenService;

    private final IValveService iValveService;

    private final IUserService iUserService;

    public PCS_000_000_010(ITokenService iTokenService, IBaseService<String> iBaseService, IValveService iValveService, IUserService iUserService) {
        this.iBaseService = iBaseService;
        this.iTokenService = iTokenService;
        this.iValveService = iValveService;
        this.iUserService = iUserService;
    }

    //设置推送开关状态
    @PostMapping(value = "/000_000_010")
    public String doPost(HttpServletRequest request) {
        //基本处理（校验session合法性）
        HashMap<String, String> resMap = iBaseService.handleRequest(request);
        String state = resMap.get("state");
        String msg = resMap.get("msg");
        String body = resMap.get("body");
        String secretKey = resMap.get("secretKey");
        if (!state.equals("000")) {
            return iBaseService.generateFail(msg);
        }
        //校验token
        JSONObject jsonObject = (JSONObject) JSON.parse(body);
        String token = jsonObject.getString("token");
        String switchState = jsonObject.getString("switchState");
        HashMap<String, String> tokenResMap = iTokenService.verifier(token);
        String tokenState = tokenResMap.get("state");
        String tokenMsg = tokenResMap.get("msg");
        if (!tokenState.equals("000")) {
            return iBaseService.generateFail(tokenMsg);
        }
        //根据userId获取权限
        long tokenUserId = Long.parseLong(tokenResMap.get("userId"));
        UserBean tokenUserBean = iUserService.getUserForId(tokenUserId);
        Integer userPermission = tokenUserBean.userPermission;
        if (userPermission != 0) {
            return iBaseService.generateFail("对不起！您没有权限关闭推送系统！");
        }
        iValveService.setValveState(switchState);
        return iBaseService.generateSucceed(secretKey, "设置成功！");
    }

}
